﻿using SwanEngine.core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace SwanEngine.Astar
{
    /// <summary>
    /// 寻路代理
    /// </summary>
    public class FindPathProxy : BaseManager<FindPathProxy>
    {
        public MyAstar1 astar;
        public MapDataVo dataVO;

        protected override void OnInit()
        {
            astar = new MyAstar1();
        }

        public void SetMapData(MapDataVo dataVO)
        {
            this.dataVO = dataVO;
            astar.Init(dataVO);
        }

        public List<Vector3> FindPathByWorldPos(Vector3 pos, Vector3 endPos)
        {
            Vector2 startPos2D = World2Tile(new Vector2(pos.x, pos.z));
            Vector2 endPos2D = World2Tile(new Vector2(endPos.x, endPos.z));

            float _time = Time.realtimeSinceStartup;

            List<Vector2> list = astar.FindPath(startPos2D, endPos2D, 0, true);
            Debug.Log("寻路消耗:" + ((Time.realtimeSinceStartup - _time) * 1000) + " ms");

            List<Vector3> list3D = PathTileToWorld(list);
            
            Debug.Log("寻路长度："+ list3D.Count);
            return list3D;
        }

        /// <summary>
        /// 格子路径转世界坐标路径
        /// </summary>
        public List<Vector3> PathTileToWorld(List<Vector2> path2D)
        {
            List<Vector3> path3D = new List<Vector3>();
            if (path2D == null) return path3D;

            for (int i = 0; i < path2D.Count; i++)
            {
                Vector2 world = Tile2World(path2D[i]);
                path3D.Add(world.To3D());
            }
            return path3D;
        }

        public Vector2 World2Tile(Vector2 pos)
        {
            pos *= dataVO.gridScale;
            return new Vector2((int)(pos.x - dataVO.offsetX), (int)(pos.y - dataVO.offsetZ));
        }

        public Vector2 Tile2World(Vector2 pos)
        {
            pos /= dataVO.gridScale;
            return new Vector2((int)(pos.x + dataVO.offsetX), (int)(pos.y + dataVO.offsetZ));
        }
    }
}